const fs = require('fs')
const path = require('path')

/**
 * 获取目录下的所有文件的路径 (仅限文件，不会记录目录)
 * @param url 目录的绝对路径
 * @returns Array
 * */
function traverseTheFile(url) {

  let dirPath = [{ type: 'dir', path: url, name: 'root' }]
  let filePath = [] // 文件路径列表

  // 循环方式遍历文件夹
  while (dirPath.length) {
    try {
      // 记住子目录
      // filePath.push({ type: 'dir', path: dirPath[0].path, name: dirPath[0].name })

      fs.readdirSync(dirPath[0].path).forEach(name => {
        let pathStr = path.normalize(dirPath[0].path + '/' + name)

        if (fs.statSync(pathStr).isDirectory()) {
          // 目录
          dirPath.push({ path: pathStr, name: name })
        } else if (fs.statSync(pathStr).isFile()) {
          // 文件
          filePath.push({ path: pathStr, name: name, extname: path.extname(name) })
        }
      })

      dirPath.splice(0, 1)
    } catch (e) {
      dirPath.splice(0, 1)
      break
    }
  }

  return filePath
}

/**
 * 为html文件中引入的的css和script的路径添加hash
 *
 *
 *
 *
 * */
function setSrcHash(htmlStr, options, hash) {
  let index = 0
  let bool = true
  let links = []
  let scripts = []

  while (bool) {
    let sIndex = htmlStr.indexOf('<script', index)
    let tIndex = sIndex != -1 ? htmlStr.indexOf('<\/script>', sIndex) : -1

    // if 和 else 中都是script标签之外的内容
    if (sIndex === -1) {
      // 末尾部分
      let s = htmlStr.substring(index)
      links = links.concat(s.match(/(<link\b[^>]*href=["'](?!http)[^>]+)(\.css["'][^>]*>)/igm) || [])
    } else {
      // 开头和夹在script标签之间的部分
      let s = htmlStr.substring(index, sIndex)
      links = links.concat(s.match(/(<link\b[^>]*href=["'](?!http)[^>]+)(\.css["'][^>]*>)/igm) || [])
      index = tIndex + 9
    }

    // 属于script标签的内容
    if (sIndex !== -1 && tIndex !== -1) {
      // console.log(htmlStr.substring(sIndex, tIndex + 9));
      let s = htmlStr.substring(sIndex, tIndex + 9)
      if (/<script\b[^>]*src="(?!http)[^>]+\.js"[^>]*>/im.test(s)) {
        scripts.push(s)
      }
    }

    bool = sIndex !== -1
  }

  // -------------------------------------------------------
  links.forEach(m => {
    let url = m.replace(/(<link\b[^>]*href=["'])([^>]+\.css)(["'][^>]*>)/im, '$2') // 获取相对路径
    let abs_url = path.normalize(path.resolve(path.dirname(options.filePath), url)) // 计算出源文件绝对路径

    if (!options.exclude.includes(abs_url)) {
      let extname = path.extname(url)
      let reg = new RegExp('(' + extname + ')$')
      let ele = m.replace(url, url.replace(reg, '.' + hash + '$1'))
      htmlStr = htmlStr.replace(m, ele)
    }
  })

  scripts.forEach(m => {
    let url = m.replace(/(<script\b[^>]*src=["'])([^>]+\.js)(["'][^>]*>.*<\/script>)/im, '$2') // 获取相对路径
    let abs_url = path.normalize(path.resolve(path.dirname(options.filePath), url)) // 计算出源文件绝对路径

    if (!options.exclude.includes(abs_url)) {
      let extname = path.extname(url)
      let reg = new RegExp('(' + extname + ')$')
      let ele = m.replace(url, url.replace(reg, '.' + hash + '$1'))
      htmlStr = htmlStr.replace(m, ele)
    }
  })

  return htmlStr
}

module.exports = { traverseTheFile, setSrcHash }
